import { cn } from "common-web";
import type { HTMLAttributes, LiHTMLAttributes, VNode } from "vue";
import { Fragment } from "vue";

type ListProps<T> = {
  header?: VNode | undefined;
  footer?: VNode | undefined;
  bordered?: boolean | undefined;
  dataSource?: T[] | undefined;
  renderItem?: (item: T, index: number) => VNode | undefined;
  rowKey?: (item: T) => string | number;
} & HTMLAttributes;

// 可以看到，这里不需要像 panel 那样搞丑陋的 slots
export default function List<T>({ header, footer, bordered, dataSource, renderItem, rowKey, ...p }: ListProps<T>) {
  const borderClass = bordered && "border border-gray-300 rounded-md shadow-sm";

  return (
    <div class={cn("w-full", borderClass, p.class)}>
      {header && <div class="px-4 py-3 border-b border-gray-200">{header}</div>}
      <div>
        <ul class="divide-y divide-gray-200">
          {dataSource?.map((item, index) => (
            <Fragment key={rowKey?.(item)}>{renderItem?.(item, index)}</Fragment>
          ))}
        </ul>
      </div>
      {footer && <div class="px-4 py-3 border-t border-gray-200">{footer}</div>}
    </div>
  );
}

type ListItemProps = {
  className?: string | undefined;
} & LiHTMLAttributes;

type ListItemSlots = {
  default?: () => VNode | undefined;
};

export function ListItem(p: ListItemProps, { slots }: { slots: ListItemSlots }) {
  return <li class={cn("py-2 px-4 hover:bg-gray-50 cursor-pointer", p.className)}>{slots.default?.()}</li>;
}
